package com.binc.testspring.study.nio;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileName: Test1
 * Autho: binC
 * Date:  2022/4/14 15:11
 */
public class Test1 {
    public static void main(String[] args) throws IOException {
        String content = "hello,上鬼鬼;";
        //1 创建一个文件的输出流
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\123.txt");
        //2 通过一个文件输出流 获得一个channel
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer  bf = ByteBuffer.allocate(1600);
        bf.put(content.getBytes("Utf-8"));
        bf.flip();
        // channel.read(bf);
        channel.write(bf);
    }

    @Test
    public void test() throws IOException {
        File f = new File("D:\\123.txt");
        FileInputStream file = new FileInputStream(f);
        FileChannel channel = file.getChannel();
        ByteBuffer bf = ByteBuffer.allocate((int) f.length());
        channel.read(bf);

        System.out.println(new String(bf.array()));

    }

    /**
     * 利用filechannel完成文件拷贝
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        File file = new File("D:\\123.txt");
        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        ByteBuffer bf = ByteBuffer.allocate((int) file.length());
        channel.read(bf);
        bf.flip();

        File target  =new File("D:\\456.txt");
        FileOutputStream fos = new FileOutputStream(target);
        FileChannel outChannel = fos.getChannel();
        outChannel.transferFrom(channel,0,channel.size());



    }



}
